﻿var EaBIM = {
  view: null,
  view2: null,
  viewToolBar: null,
  button_selectWindow: null,
  ModelLoadEnd: false,
  ModelLoadEnd2: false,
  baseUrl: null,
  position: null, //选中的位置
  /**初始化按钮 */
  init3DButtons: function () {
    EaBIM.viewToolBar = new Autodesk.Viewing.UI.ControlGroup("EaBIM_viewToolBar");
    EaBIM.button_selectWindow = new Autodesk.Viewing.UI.Button("EaBIM_button_selectWindow");
  },
  /**初始化右键 */
  initRightMenu: function () {
    //查找全部实例
    EaBIM.view.registerContextMenuCallback('查找全部实例', (menu, status) => {
      if (status.hasSelected) {
        menu.push({
          title: '查找全部实例',
          target: () => {
            var sel = NOP_VIEWER.getAggregateSelection();
            var totalLength = sel.reduce((acc, obj) => {
              return acc + obj.selection.length;
            }, 0);
            var i = 0;
            var selection = []
            sel.forEach(v => {
              let ids = {
                ids: [],
                model: v.model
              };
              selection.push(ids)
              v.selection.forEach(dbid => {
                var a = v.model.getData().instanceTree.getNodeName(dbid).split("[")[0].trim();
                v.model.search(a, function (data) {
                  i++;
                  ids.ids = ids.ids.concat(data);
                }, null, null, true)
              })

            })

            var inter = setInterval(() => {
              clearInterval(inter)
              if (totalLength == i) {
                EaBIM.view.impl.selector.setAggregateSelection(selection)
                // EaBIM.view.impl.visibilityManager.aggregateIsolate(selection);
              }
            }, 50);


          }
        });
      }
    });
    if (EaBIM.modelData && EaBIM.modelData.ViewType == 'tjdw') {
      // 添加点位
      EaBIM.view.registerContextMenuCallback('添加点位', (menu, status) => {
        if (status.hasSelected) {
          menu.push({
            title: '添加点位',
            target: () => {
              // 构件id
              const selSet = EaBIM.view.getSelection();
              var it = EaBIM.view.model.getData().instanceTree;
              var viewerstate = JSON.stringify(EaBIM.view.getState())
              let data = {
                pointId: selSet[0],
                pointName: it.getNodeName(selSet),
                viewerState: viewerstate,
                event: status.event,
              }
              window.addPoint(data)
            }
          })
        }

      })
    }
    if (EaBIM.modelData && EaBIM.modelData.ViewType == 'glzl') {
      // 资料关联
      EaBIM.view.registerContextMenuCallback('添加点位', (menu, status) => {
        if (status.hasSelected) {
          menu.push({
            title: '添加点位',
            target: () => {
              // 构件id
              const selSet = EaBIM.view.getSelection();
              var it = EaBIM.view.model.getData().instanceTree;
              var fragId1 = "";
              it.enumNodeFragments(selSet[0], function (fragId) {
                fragId1 = fragId;
              }, false);
              var viewerstate = JSON.stringify(EaBIM.view.getState())
              let data = {
                pointId: selSet[0],
                pointName: it.getNodeName(selSet),
                fragId: fragId1,
                viewerState: viewerstate,
                event: status.event,
              }
              window.addDataAssociation(data)
            }
          })
        }

      })
    }

  },
  /**获取最底层子集 */
  getLeafNodes: function (model, dbIds) {
    const instanceTree = model.getData().instanceTree
    dbIds = dbIds || instanceTree.getRootId();
    const dbIdArray = Array.isArray(dbIds) ? dbIds : [dbIds]
    let leafIds = [];
    const getLeafNodesRec = (id) => {
      let childCount = 0;
      instanceTree.enumNodeChildren(id, (childId) => {
        getLeafNodesRec(childId);
        ++childCount;
      })
      if (childCount == 0) {
        leafIds.push(id);
      }
    }
    for (let i = 0; i < dbIdArray.length; ++i) {
      getLeafNodesRec(dbIdArray[i]);
    }
    return leafIds;
  },
  /**递归获取根节点 */
  getParentLeafNodes: function (model, dbIds) {
    const instanceTree = model.getData().instanceTree
    dbIds = dbIds || instanceTree.getRootId();
    const dbIdArray = Array.isArray(dbIds) ? dbIds : [dbIds]
    let leafIds = [];
    const getLeafNodesRec = (id) => {
      let childCount = 0;
      instanceTree.enumNodeChildren(id, (childId) => {
        getLeafNodesRec(childId);
        ++childCount;
      })
      if (childCount > 0) {
        leafIds.push(id);
      }
    }
    for (let i = 0; i < dbIdArray.length; ++i) {
      getLeafNodesRec(dbIdArray[i]);
    }
    return leafIds;
  },

  /**创建按钮 */
  creatViewButton: function () {
    EaBIM.setUp_button_selectWindow();

    EaBIM.viewToolBar.addControl(EaBIM.button_selectWindow);

    EaBIM.view.toolbar.addControl(EaBIM.viewToolBar);
  },
  //模型框选
  setUp_button_selectWindow: function () {
    EaBIM.button_selectWindow.setIcon("icon-kuangxuan");
    EaBIM.button_selectWindow.setToolTip("模型框选");
    EaBIM.button_selectWindow.onClick = function (e) {
      if (!bimSelectWindow.beVisible) {
        EaBIM.startSelection();
        EaBIM.isFullScreen = !EaBIM.isFullScreen;
        bimSelectWindow.beVisible = true;
      } else {
        bimSelectWindow.beVisible = false;
      }
      EaBIM.buttonClick('#EaBIM_button_selectWindow');
    }
  },
  //框选方法
  startSelection() {
    EaBIM.view.loadExtension('MySelectionWindow').then(function (ext) {
      ext.init();
      setTimeout(function () {
        ext.handleSelect(true);
      }, 300)
    });
  },
  //加载多模型
  localManyServerModel(data) {
    EaBIM.ModelLoadEnd = false;
    try {
      document.getElementById('MyViewerDiv').innerHTML = "";
      EaBIM.view.tearDown();
      EaBIM.view = null;
      $('div.adsk-viewing-viewer label.markup').remove()
    } catch (e) { }
    var element = document.getElementById("MyViewerDiv");
    var config = {
      // extensions: [
      //   "Autodesk.Viewing.ZoomWindow",
      //   "IssuesExtension"
      // ],
      disabledExtensions: {
        measure: false,
        section: false,
      },
      memory: {
        limit: 32 * 1024 //32 GB
      },
      theme: 'light-theme'
    };
    EaBIM.view = new Autodesk.Viewing.Private.GuiViewer3D(element, config);
    var options = {
      "language": "zh-HANS",
      env: 'Local',
      offline: 'true',
      useADP: false
    };
    Autodesk.Viewing.Initializer(options, function () {
      EaBIM.view.start();
      EaBIM.view.setDisplayEdges(false);
      // Eab.LoadModelsViewer.setTheme('light-theme');
      //使用Revit 共享座标 (GIS) 对齐
      const modelOpts = {
        applyRefPoint: true,
        globalOffset: {
          x: 0,
          y: 0,
          z: 0
        },
      }
      //以模型原点对齐
      // const modelOpts = {
      //     placementTransform: new THREE.Matrix4(),
      //     globalOffset: {
      //         x: 0,
      //         y: 0,
      //         z: 0
      //     }
      // }
      data.list.forEach(v => {
        let url = data.baseUrl + v.modelPath;
        EaBIM.view.loadModel(url, modelOpts);
      });
      var i = 0;
      EaBIM.view.addEventListener(
        Autodesk.Viewing.TEXTURES_LOADED_EVENT, //!<<<< 事件名称
        function (event) {
          i++;
          if (i == data.list.length || i == data.list.length - 2) {
            i = 0;
            EaBIM.ModelLoadEnd = true;
            EaBIM.view.fitToView()
            EaBIM.initRightMenu();

            if (data.type == "right") { //初始化
              EaBIM.init3DButtons();
              EaBIM.creatViewButton()
            }
          }
        });

    });
  },
  localManyServerModel2(data) {

    EaBIM.ModelLoadEnd2 = false;
    try {
      document.getElementById('MyViewerDiv2').innerHTML = "";
      EaBIM.view2.tearDown();
      EaBIM.view2 = null;
    } catch (e) { }
    var element = document.getElementById("MyViewerDiv2");
    var config = {
      extensions: [
        "Autodesk.Viewing.ZoomWindow",
        "IssuesExtension"
      ],
      disabledExtensions: {
        measure: false,
        section: false,
      },
      memory: {
        limit: 32 * 1024 //32 GB
      },
      theme: 'light-theme'
    };
    EaBIM.view2 = new Autodesk.Viewing.Private.GuiViewer3D(element, config);
    var options = {
      "language": "zh-HANS",
      env: 'Local',
      offline: 'true',
      useADP: false
    };
    Autodesk.Viewing.Initializer(options, function () {
      EaBIM.view2.start();
      EaBIM.view2.setDisplayEdges(false);
      // Eab.LoadModelsViewer.setTheme('light-theme');
      //使用Revit 共享座标 (GIS) 对齐
      const modelOpts = {
        applyRefPoint: true,
        globalOffset: {
          x: 0,
          y: 0,
          z: 0
        },
      }
      //以模型原点对齐
      // const modelOpts = {
      //     placementTransform: new THREE.Matrix4(),
      //     globalOffset: {
      //         x: 0,
      //         y: 0,
      //         z: 0
      //     }
      // }
      data.list.forEach(v => {
        let url = data.baseUrl + v.modelPath;
        EaBIM.view2.loadModel(url, modelOpts);
      });
      var i = 0;
      EaBIM.view2.addEventListener(
        Autodesk.Viewing.TEXTURES_LOADED_EVENT, //!<<<< 事件名称
        function (event) {
          i++;
          if (i == data.list.length) {
            i = 0;
            EaBIM.ModelLoadEnd2 = true;
            EaBIM.view2.fitToView()
          }
        });

    });
  },
  // 加载单个模型
  localOneServerModel(data) {
    try {
      document.getElementById('MyViewerDiv').innerHTML = "";
      EaBIM.view.tearDown();
    } catch { };
    if (!data.list) {
      console.error("数据配置错误");
      return false;
    }
    EaBIM.ModelLoadEnd = false;
    EaBIM.modelData = data;
    var viewerElement = document.getElementById('MyViewerDiv');
    var options = {
      'model': "",
      "language": "zh-HANS",
      env: 'Local',
      offline: 'true',
      useADP: false,
      offlineResourcePrefix: ""
    };
    options.model = data.baseUrl + data.list.url;

    options.offlineResourcePrefix = options.model.substring(0, options.model.lastIndexOf('/'));
    var config = {
      extensions: [
        "Autodesk.Viewing.ZoomWindow",
        "Autodesk.AEC.Minimap3DExtension",
        "Autodesk.AEC.LevelsExtension",
        "IssuesExtension"
      ],
      disabledExtensions: {
        measure: false,
        section: false,
      },
      memory: {
        limit: 32 * 1024 //32 GB
      },
      theme: 'light-theme'
    };

    EaBIM.view = new Autodesk.Viewing.Private.GuiViewer3D(viewerElement, config);
    Autodesk.Viewing.Initializer(options, function () {
      EaBIM.view.addEventListener(
        Autodesk.Viewing.SELECTION_CHANGED_EVENT, //!<<<< 事件名称
        function (event) {
          var sel = NOP_VIEWER.getSelection();
          // console.log(sel)
          //考察选择集中第一个对象的属性信息
          NOP_VIEWER.getProperties(sel[0], function (objProp) {
            if (objProp) {
              console.log(objProp);
              //遍历每个属性
              // for (var index in objProp.properties) {
              //     var Prop = objProp.properties[index];
              //     console.log('name: ' + Prop.displayName + '    value:    ' + Prop.displayValue);
              // }
            }
          });
        });
      //EaBIM.view.loadExtension('CustomPropertyPanelExtension').then(function (externalExtension) {

      //});
      EaBIM.view.start();
      let documentPath = decodeURIComponent(options.offlineResourcePrefix + "/manifest-model.json");
      Autodesk.Viewing.Document.load(documentPath, (doc) => {
        doc.downloadAecModelData();
        var viewable = doc.getRoot().getDefaultGeometry();
        EaBIM.view.loadDocumentNode(doc, viewable, {}).then();
      }, (error) => {
        EaBIM.view.loadModel(options.model, {
          isAEC: true
        });
      });
      EaBIM.view.setDisplayEdges(false);
      EaBIM.onLoadSuccess(data);
      EaBIM.view.addEventListener(
        Autodesk.Viewing.TEXTURES_LOADED_EVENT, //!<<<< 事件名称
        function (event) {
          EaBIM.ModelLoadEnd = true;
          EaBIM.initRightMenu();
          EaBIM.view.fitToView(true);
          try {
            EaBIM.view.getExtension("Autodesk.Measure").sharedMeasureConfig.units = "mm";
            EaBIM.view.setDisplayEdges(false);
          } catch (error) {

          }
        });
    })
  },


  //#region 计算面积

  // Sends component geometry to the web worker
  postComponent(dbId) {

    const geometry = EaBIM.getComponentGeometry(dbId)

    const msg = {
      boundingBox: EaBIM.getComponentBoundingBox(dbId),
      matrixWorld: geometry.matrixWorld,
      nbMeshes: geometry.meshes.length,
      msgId: 'MSG_ID_COMPONENT',
      dbId
    }

    geometry.meshes.forEach((mesh, idx) => {

      msg['positions' + idx] = mesh.positions
      msg['indices' + idx] = mesh.indices
      msg['stride' + idx] = mesh.stride
    })
    var mesh = EaBIM.buildComponentMesh(msg)
    return EaBIM.calculateVolume(mesh);
  },
  volumeOfT(p1, p2, p3) {
    var v321 = p3.x * p2.y * p1.z;
    var v231 = p2.x * p3.y * p1.z;
    var v312 = p3.x * p1.y * p2.z;
    var v132 = p1.x * p3.y * p2.z;
    var v213 = p2.x * p1.y * p3.z;
    var v123 = p1.x * p2.y * p3.z;
    return (-v321 + v231 + v312 - v132 - v213 + v123) / 6.0;
  },

  calculateVolume(object) {
    var volumes = 0.0;

    for (var i = 0; i < object.geometry.faces.length; i++) {
      var Pi = object.geometry.faces[i].a;
      var Qi = object.geometry.faces[i].b;
      var Ri = object.geometry.faces[i].c;

      var P = new THREE.Vector3(object.geometry.vertices[Pi].x, object.geometry.vertices[Pi].y, object.geometry.vertices[Pi].z);
      var Q = new THREE.Vector3(object.geometry.vertices[Qi].x, object.geometry.vertices[Qi].y, object.geometry.vertices[Qi].z);
      var R = new THREE.Vector3(object.geometry.vertices[Ri].x, object.geometry.vertices[Ri].y, object.geometry.vertices[Ri].z);
      volumes += EaBIM.volumeOfT(P, Q, R);
    }
    return Math.abs(volumes);
  },
  // get geometry for all fragments in a component
  getComponentGeometry(dbId) {

    const fragIds = EaBIM.getLeafFragIds(
      EaBIM.view.model, dbId)

    let matrixWorld = null

    const meshes = fragIds.map((fragId) => {

      const renderProxy = EaBIM.view.impl.getRenderProxy(
        EaBIM.view.model,
        fragId)
      const geometry = renderProxy.geometry

      const attributes = geometry.attributes

      const positions = geometry.vb
        ? geometry.vb
        : attributes.position.array

      const indices = attributes.index.array || geometry.ib

      const stride = geometry.vb ? geometry.vbstride : 3

      const offsets = geometry.offsets

      matrixWorld = matrixWorld ||
        renderProxy.matrixWorld.elements

      return {
        positions,
        indices,
        offsets,
        stride
      }
    })

    return {
      matrixWorld,
      meshes
    }
  },
  getComponentBoundingBox(dbId) {
    const model = EaBIM.view.model

    const fragIds = EaBIM.getLeafFragIds(
      model, dbId)

    const fragList = model.getFragmentList()

    return EaBIM.getModifiedWorldBoundingBox(
      fragIds, fragList)
  },
  getComponentBoundingBox2(dbId, viewer) {
    EaBIM.view = viewer;
    const model = EaBIM.view.model

    const fragIds = EaBIM.getLeafFragIds(
      model, dbId)

    const fragList = model.getFragmentList()

    return EaBIM.getModifiedWorldBoundingBox(
      fragIds, fragList)
  },
  getModifiedWorldBoundingBox(fragIds, fragList) {
    const fragbBox = new THREE.Box3()
    const nodebBox = new THREE.Box3()

    fragIds.forEach(function (fragId) {
      fragList.getWorldBounds(fragId, fragbBox)

      nodebBox.union(fragbBox)
    })

    return nodebBox
  },
  getLeafFragIds(model, leafId) {
    if (model.getData().instanceTree) {
      const it = model.getData().instanceTree

      const fragIds = []

      it.enumNodeFragments(
        leafId, (fragId) => {
          fragIds.push(fragId)
        })

      return fragIds
    } else {
      const fragments = model.getData().fragments

      const fragIds = fragments.dbId2fragId[leafId]

      return !Array.isArray(fragIds)
        ? [fragIds]
        : fragIds
    }
  },

  // On the worker side reconstruct THREE.Mesh
  // from received data and create ThreeBSP
  buildComponentMesh(data) {

    const vertexArray = []

    for (let idx = 0; idx < data.nbMeshes; ++idx) {

      const meshData = {
        positions: data['positions' + idx],
        indices: data['indices' + idx],
        stride: data['stride' + idx]
      }

      EaBIM.getMeshGeometry(meshData, vertexArray)
    }

    const geometry = new THREE.Geometry()

    for (var i = 0; i < vertexArray.length; i += 3) {

      geometry.vertices.push(vertexArray[i])
      geometry.vertices.push(vertexArray[i + 1])
      geometry.vertices.push(vertexArray[i + 2])

      const face = new THREE.Face3(i, i + 1, i + 2)

      geometry.faces.push(face)
    }

    const matrixWorld = new THREE.Matrix4()

    matrixWorld.fromArray(data.matrixWorld)

    const mesh = new THREE.Mesh(geometry)

    mesh.applyMatrix(matrixWorld)

    mesh.boundingBox = data.boundingBox

    // mesh.bsp = new ThreeBSP(mesh)

    mesh.dbId = data.dbId

    return mesh
  },

  getMeshGeometry(data, vertexArray) {

    const offsets = [{
      count: data.indices.length,
      index: 0,
      start: 0
    }
    ]

    for (var oi = 0, ol = offsets.length; oi < ol; ++oi) {

      var start = offsets[oi].start
      var count = offsets[oi].count
      var index = offsets[oi].index

      for (var i = start, il = start + count; i < il; i += 3) {

        const a = index + data.indices[i]
        const b = index + data.indices[i + 1]
        const c = index + data.indices[i + 2]

        const vA = new THREE.Vector3()
        const vB = new THREE.Vector3()
        const vC = new THREE.Vector3()

        vA.fromArray(data.positions, a * data.stride)
        vB.fromArray(data.positions, b * data.stride)
        vC.fromArray(data.positions, c * data.stride)

        vertexArray.push(vA)
        vertexArray.push(vB)
        vertexArray.push(vC)
      }
    }
  },
  //#endregion


  //#region 计算面积2
  getVolume(viewer, dbId) {
    var volume = 0;
    var it = viewer.model.getData().instanceTree;

    it.enumNodeFragments(dbId, function (fragId) {
      EaBIM.getVertices(viewer, fragId, (p1, p2, p3) => {
        volume += EaBIM.getTriangleVolume(p1, p2, p3)
      })
    }, true);

    return volume;
  },

  getSurfaceArea(viewer, dbId) {
    var area = 0;
    var it = viewer.model.getData().instanceTree;

    it.enumNodeFragments(dbId, function (fragId) {
      EaBIM.getVertices(viewer, fragId, (p1, p2, p3) => {
        area += EaBIM.getTriangleArea(p1, p2, p3)
      })
    }, true);

    return area * 0.09290304;
  },

  getTriangleArea(p1, p2, p3) {
    var tr = new THREE.Triangle(p1, p2, p3);
    return tr.area();
  },

  getTriangleVolume(p1, p2, p3) {
    return p1.dot(p2.cross(p3)) / 6.0;
  },

  getVertices(viewer, fragId, callback) {
    var fragProxy = viewer.impl.getFragmentProxy(
      viewer.model,
      fragId);

    var renderProxy = viewer.impl.getRenderProxy(
      viewer.model,
      fragId);

    fragProxy.updateAnimTransform();

    var matrix = new THREE.Matrix4();
    fragProxy.getWorldMatrix(matrix);

    var geometry = renderProxy.geometry;

    var attributes = geometry.attributes;

    var vA = new THREE.Vector3();
    var vB = new THREE.Vector3();
    var vC = new THREE.Vector3();

    if (attributes.index !== undefined) {

      var indices = attributes.index.array || geometry.ib;
      var positions = geometry.vb ? geometry.vb : attributes.position.array;
      var stride = geometry.vb ? geometry.vbstride : 3;
      var offsets = geometry.offsets;

      if (!offsets || offsets.length === 0) {

        offsets = [{ start: 0, count: indices.length, index: 0 }];
      }

      for (var oi = 0, ol = offsets.length; oi < ol; ++oi) {

        var start = offsets[oi].start;
        var count = offsets[oi].count;
        var index = offsets[oi].index;

        for (var i = start, il = start + count; i < il; i += 3) {

          var a = index + indices[i];
          var b = index + indices[i + 1];
          var c = index + indices[i + 2];

          vA.fromArray(positions, a * stride);
          vB.fromArray(positions, b * stride);
          vC.fromArray(positions, c * stride);

          vA.applyMatrix4(matrix);
          vB.applyMatrix4(matrix);
          vC.applyMatrix4(matrix);

          callback(vA, vB, vC)
        }
      }
    }
    else {
      var positions = geometry.vb ? geometry.vb : attributes.position.array;
      var stride = geometry.vb ? geometry.vbstride : 3;

      for (var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9) {

        var a = i;
        var b = i + 1;
        var c = i + 2;

        vA.fromArray(positions, a * stride);
        vB.fromArray(positions, b * stride);
        vC.fromArray(positions, c * stride);

        vA.applyMatrix4(matrix);
        vB.applyMatrix4(matrix);
        vC.applyMatrix4(matrix);

        callback(vA, vB, vC)
      }
    }
  },
  //#endregion
















  //在线离线加载
  localServerModels: function (data) {
    try {
      document.getElementById('MyViewerDiv').innerHTML = "";
      EaBIM.view.tearDown();
    } catch { };
    if (!data.list) {
      console.error("数据配置错误");
      return false;
    }
    EaBIM.ModelLoadEnd = false;
    EaBIM.modelData = data;
    var viewerElement = document.getElementById('MyViewerDiv');
    var options = {
      'model': "",
      "language": "zh-HANS",
      env: 'Local',
      offline: 'true',
      useADP: false,
      offlineResourcePrefix: ""
    };
    options.model = data.baseUrl + data.list[0].modelPath;
    options.offlineResourcePrefix = options.model.substring(0, options.model.lastIndexOf('/'));
    var config = {
      extensions: [
        "Autodesk.Viewing.ZoomWindow",
        "Autodesk.AEC.Minimap3DExtension",
        "Autodesk.AEC.LevelsExtension",
      ],
      disabledExtensions: {
        measure: false,
        section: false,
      },
      memory: {
        limit: 32 * 1024 //32 GB
      },
      theme: 'light-theme'
    };

    EaBIM.view = new Autodesk.Viewing.Private.GuiViewer3D(viewerElement, config);
    Autodesk.Viewing.Initializer(options, function () {
      // EaBIM.view.addEventListener(
      //     Autodesk.Viewing.SELECTION_CHANGED_EVENT, //!<<<< 事件名称
      //     function (event) {
      //         EaBIM.PropertyPanel();
      //         var sel = NOP_VIEWER.getSelection();
      //         // console.log(sel)
      //         //考察选择集中第一个对象的属性信息
      //         NOP_VIEWER.getProperties(sel[0], function (objProp) {
      //             if (objProp) {
      //                 // console.log(objProp);
      //                 //遍历每个属性
      //                 // for (var index in objProp.properties) {
      //                 //     var Prop = objProp.properties[index];
      //                 //     console.log('name: ' + Prop.displayName + '    value:    ' + Prop.displayValue);
      //                 // }
      //             }
      //         });
      //     });
      //EaBIM.view.loadExtension('CustomPropertyPanelExtension').then(function (externalExtension) {

      //});
      EaBIM.view.start();
      let documentPath = decodeURIComponent(options.offlineResourcePrefix + "/manifest-model.json");
      Autodesk.Viewing.Document.load(documentPath, (doc) => {
        doc.downloadAecModelData();
        var viewable = doc.getRoot().getDefaultGeometry();
        EaBIM.view.loadDocumentNode(doc, viewable, {}).then();
      }, (error) => {
        EaBIM.view.loadModel(options.model, {
          isAEC: true
        });
      });
      EaBIM.view.setDisplayEdges(false);
      EaBIM.onLoadSuccess(data);
      EaBIM.view.addEventListener(
        Autodesk.Viewing.TEXTURES_LOADED_EVENT, //!<<<< 事件名称
        function (event) {
          EaBIM.ModelLoadEnd = true;
          EaBIM.initRightMenu();
          EaBIM.view.fitToView(true);
          try {
            EaBIM.view.getExtension("Autodesk.Measure").sharedMeasureConfig.units = "mm";
            EaBIM.view.setDisplayEdges(false);
          } catch (error) {

          }
        });
    })
  },
  resize: function () {
    if (EaBIM.view)
      EaBIM.view.resize();
  },
  fitToView: function (data) {
    var view = EaBIM.view.impl.modelQueue().getModels().filter(x => x.loader.svfUrn.indexOf(data.modelId) > 0);
    if (view.length > 0) {
      EaBIM.view.fitToView(data.dbId, view[0])
      if (data.select) {
        EaBIM.view.impl.selector.setAggregateSelection([{
          ids: data.dbId,
          model: view[0]
        }])
      }
    }
  },

  getAggregateSelection: function () {
    var select = EaBIM.view.getAggregateSelection()
    var m = []
    select.forEach(v => {
      m.push({
        dbIds: v.selection,
        modelId: v.model.loader.svfUrn.split("/")[7]
      })
    })
    return m
  },

  getModelLableXYZ: function (event) {
    try {
      let position = EaBIM.view.clientToWorld(
        event.offsetX,
        event.offsetY,
        false
      ).intersectPoint;
      var select = EaBIM.view.getAggregateSelection()
      if (select.length != 1) {
        EaBIM.position = null;
      } else {
        EaBIM.position = {
          xyz: position,
          dbId: select[0].selection[0],
          modelId: select[0].model.loader.svfUrn.split("/")[7]
        };
      }
    } catch (error) {
      EaBIM.position = null;
    } finally {
      return EaBIM.position;
    }

  },
  // 竣工打标
  CreateMarkUpsJG(data, color) {
    var inter = setInterval(() => {
      if (EaBIM.ModelLoadEnd && EaBIM.view.model.getInstanceTree()) {
        clearInterval(inter)
        // 上色
        if (color) {
          data.forEach(v => {
            let colors = v.tempcolor.replace(/[a-zA-Z()]/g, '').split(",")
            EaBIM.view.setThemingColor(Number(v.dbid), new THREE.Vector4(Number(colors[0]) / 255, Number(colors[1]) / 255, Number(colors[2]) / 255, Number(colors[3])))
          })
        }
        EaBIM.view.getExtension("IssuesExtension")._removeMarkups()
        EaBIM.view.getExtension("IssuesExtension")._createJGMarkups(data);
      }
    }, 500);
  },
  CreateMarkUps(data) {
    var inter = setInterval(() => {
      if (EaBIM.ModelLoadEnd && EaBIM.view.model.getInstanceTree()) {
        clearInterval(inter)
        EaBIM.view.getExtension("IssuesExtension")._removeMarkups()
        EaBIM.view.getExtension("IssuesExtension")._createMarkups(data);
      }
    }, 500);
  },
  buttonClick: function (button) {
    if ($(button).hasClass("inactive")) {
      $(button).removeClass("inactive").addClass("active");
    } else {
      $(button).removeClass("active").addClass("inactive");
    }
  },
  onLoadSuccess: function () {
    console.log("模型加载成功");
  },
}
var Base64 = {
  //字符串转base64
  encode(str) {
    // 对字符串进行编码
    var encode = encodeURI(str);
    // 对编码的字符串转化base64
    var base64 = btoa(encode);
    return base64;
  },
  decode(base64) {
    // 对base64转编码
    var decode = atob(base64);
    // 编码转字符串
    var str = decodeURI(decode);
    return str;
  }
}
